package com.base.api.controller.wxSign;

import com.base.log.WebLog;
import com.base.mapper.voipmapper.UsersConfigNewMapper;
import com.base.po.acess.TokenUtils;
import com.base.po.voip.UsersConfigNew;
import com.base.result.ResponseResult;
import com.base.result.ResponseResultUtils;
import com.base.self.common.SelfRuntimeException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 微信接口
 *
 * @author K.
 */
@Api(tags = "微信jsapi支付获取")
@RestController
@RequestMapping("/wxSign")
@Slf4j
public class WxAuthController {

    private final UsersConfigNewMapper usersConfigNewMapper;

    private final WxTokenContext wxTokenContext;

    public WxAuthController(UsersConfigNewMapper usersConfigNewMapper,
                            WxTokenContext wxTokenContext) {
        this.usersConfigNewMapper = usersConfigNewMapper;
        this.wxTokenContext = wxTokenContext;
    }


    @ApiOperation(value="微信端获取token")
    @RequestMapping(value = "/wxGetToken", method = RequestMethod.POST)
    @CrossOrigin
    @WebLog
    public ResponseResult wxGetToken(@ApiParam(value = "手机号") @RequestParam String Mobile,
                                     @ApiParam(value = "代理商id") @RequestParam String ParentId)  {
        if(StringUtils.isEmpty(Mobile) || StringUtils.isEmpty(ParentId)) {
            return ResponseResultUtils.getResponseResultF("参数异常");
        }
        String encryptResult = TokenUtils.getToken(ParentId, Mobile);
        log.warn("{}:{} token: {}", ParentId, Mobile, encryptResult);
        return ResponseResultUtils.getResponseResultDataS(encryptResult);
    }

    @ApiOperation(value="微信用户授权")
    @RequestMapping(value = "/authorize", method = RequestMethod.POST)
    @WebLog
    public ResponseResult authorize(@ApiParam(value = "代理商id") @RequestParam String parentId,
                                    @ApiParam(value = "code") @RequestParam String code) {
        if(StringUtils.isEmpty(code) || StringUtils.isEmpty(parentId)) {
            return ResponseResultUtils.getResponseResultF("参数异常");
        }

        UsersConfigNew config = usersConfigNewMapper.selectByParentId(parentId);
        Optional.ofNullable(config).orElseThrow(() -> new SelfRuntimeException(ResponseResultUtils.getResponseResultF("代理商配置错误")));
        String appId = config.getWxMpAppid();
        String secret = config.getWxMpAppsecret();
        String qrCode = config.getWxMpQRCode();

        try {
            final WXAccessToken wxAccessToken = wxTokenContext.getAccessTokenByOauth2(appId, secret, code);
            String token = wxTokenContext.getTokeFromRedis(appId, secret);
            if (StringUtils.isEmpty(token)) {
                return ResponseResultUtils.getResponseResultF("授权失败,获取Token失败。");
            }
            final WXCgiBinUserInfo wxCgiBinUserInfo = wxTokenContext.getUserInfo(token, wxAccessToken.getOpenid());
            if (wxCgiBinUserInfo.getSubscribe() != null && StringUtils.isNotEmpty(wxCgiBinUserInfo.getOpenid())) {
//                Map<String, Object> data = new HashMap<>();
//                data.put("parentId", parentId);
//                data.put("wxQRCode", qrCode);
                return ResponseResultUtils.getResponseResultS("授权成功", wxCgiBinUserInfo);
            }
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResultUtils.getResponseResultF("授权异常：" + e.getMessage());
        }
        return ResponseResultUtils.getResponseResultF("授权失败");
    }

}
